import React, { useState } from 'react';
import { Card, List, Button, message } from 'antd';

const DragSwap = () => {
  // 初始数据状态，分别存储两个列表的内容
  const [listA, setListA] = useState(['Item 1', 'Item 2', 'Item 3']);
  const [listB, setListB] = useState(['Item A', 'Item B', 'Item C']);
  const [draggedItem, setDraggedItem] = useState(null);
  const [draggedFrom, setDraggedFrom] = useState(null); // 记录数据来自哪个列表

  // 处理拖拽开始事件
  const handleDragStart = (item, list) => {
    setDraggedItem(item);
    setDraggedFrom(list);
  };

  // 处理拖拽放下事件
  const handleDrop = (list) => {
    if (draggedFrom !== list) {
      if (list === 'A') {
        // 交换到 List A
        setListA((prev) => [...prev, draggedItem]);
        setListB((prev) => prev.filter((item) => item !== draggedItem));
      } else {
        // 交换到 List B
        setListB((prev) => [...prev, draggedItem]);
        setListA((prev) => prev.filter((item) => item !== draggedItem));
      }
      message.success(`Moved "${draggedItem}" to List ${list}`);
    }
    setDraggedItem(null);
    setDraggedFrom(null);
  };

  // 渲染拖拽项
  const renderDraggableItem = (item, list) => (
    <div
      draggable
      onDragStart={() => handleDragStart(item, list)}
      style={{
        padding: '8px',
        margin: '4px 0',
        backgroundColor: '#f0f0f0',
        border: '1px solid #ddd',
        borderRadius: '4px',
        cursor: 'move',
      }}
    >
      {item}
    </div>
  );

  return (
    <div style={{ display: 'flex', gap: '20px' }}>
      <Card
        title="List A"
        style={{ width: '45%' }}
        onDragOver={(e) => e.preventDefault()}
        onDrop={() => handleDrop('A')}
      >
        <List>
          {listA.map((item, index) => (
            <List.Item key={index}>{renderDraggableItem(item, 'A')}</List.Item>
          ))}
        </List>
      </Card>

      <Card
        title="List B"
        style={{ width: '45%' }}
        onDragOver={(e) => e.preventDefault()}
        onDrop={() => handleDrop('B')}
      >
        <List>
          {listB.map((item, index) => (
            <List.Item key={index}>{renderDraggableItem(item, 'B')}</List.Item>
          ))}
        </List>
      </Card>
    </div>
  );
};

export default DragSwap;
